package com.koushikdutta.async.http;

import android.net.Uri;
import com.koushikdutta.async.ArrayDeque;
import com.koushikdutta.async.AsyncSocket;
import com.koushikdutta.async.ByteBufferList;
import com.koushikdutta.async.DataEmitter;
import com.koushikdutta.async.NullDataCallback;
import com.koushikdutta.async.callback.CompletedCallback;
import com.koushikdutta.async.callback.ConnectCallback;
import com.koushikdutta.async.future.SimpleCancellable;
import com.koushikdutta.async.http.AsyncHttpClientMiddleware.GetSocketData;
import com.koushikdutta.async.http.AsyncHttpClientMiddleware.OnRequestCompleteData;
import java.util.Hashtable;

public class AsyncSocketMiddleware extends SimpleMiddleware {
    boolean connectAllAddresses;
    Hashtable<String, ConnectionInfo> connectionInfo;
    int idleTimeoutMs;
    protected AsyncHttpClient mClient;
    int maxConnectionCount;
    int port;
    String proxyHost;
    int proxyPort;
    String scheme;

    static class ConnectionInfo {
        int openCount;
        ArrayDeque<GetSocketData> queue = new ArrayDeque();
        ArrayDeque<IdleSocketHolder> sockets = new ArrayDeque();

        ConnectionInfo() {
        }
    }

    class IdleSocketHolder {
        long idleTime = System.currentTimeMillis();
        AsyncSocket socket;

        public IdleSocketHolder(AsyncSocket socket) {
            this.socket = socket;
        }
    }

    public AsyncSocketMiddleware(AsyncHttpClient client, String scheme, int port) {
        this.idleTimeoutMs = 300000;
        this.connectionInfo = new Hashtable();
        this.maxConnectionCount = Integer.MAX_VALUE;
        this.mClient = client;
        this.scheme = scheme;
        this.port = port;
    }

    public int getSchemePort(Uri uri) {
        if (uri.getScheme() == null || !uri.getScheme().equals(this.scheme)) {
            return -1;
        }
        if (uri.getPort() == -1) {
            return this.port;
        }
        return uri.getPort();
    }

    public AsyncSocketMiddleware(AsyncHttpClient client) {
        this(client, "http", 80);
    }

    protected ConnectCallback wrapCallback(ConnectCallback callback, Uri uri, int port, boolean proxied) {
        return callback;
    }

    public void setConnectAllAddresses(boolean connectAllAddresses) {
        this.connectAllAddresses = connectAllAddresses;
    }

    String computeLookup(Uri uri, int port, String proxyHost, int proxyPort) {
        String proxy;
        if (proxyHost != null) {
            proxy = proxyHost + ":" + proxyPort;
        } else {
            proxy = "";
        }
        if (proxyHost != null) {
            proxy = proxyHost + ":" + proxyPort;
        }
        return uri.getScheme() + "//" + uri.getHost() + ":" + port + "?proxy=" + proxy;
    }

    /* JADX WARNING: inconsistent code. */
    /* Code decompiled incorrectly, please refer to instructions dump. */
    public com.koushikdutta.async.future.Cancellable getSocket(com.koushikdutta.async.http.AsyncHttpClientMiddleware.GetSocketData r19) {
        /*
        r18 = this;
        r0 = r19;
        r13 = r0.request;
        r12 = r13.getUri();
        r0 = r19;
        r13 = r0.request;
        r13 = r13.getUri();
        r0 = r18;
        r5 = r0.getSchemePort(r13);
        r13 = -1;
        if (r5 != r13) goto L_0x001b;
    L_0x0019:
        r7 = 0;
    L_0x001a:
        return r7;
    L_0x001b:
        r0 = r19;
        r13 = r0.request;
        r13 = r13.getProxyHost();
        r0 = r19;
        r14 = r0.request;
        r14 = r14.getProxyPort();
        r0 = r18;
        r4 = r0.computeLookup(r12, r5, r13, r14);
        r0 = r18;
        r3 = r0.getOrCreateConnectionInfo(r4);
        monitor-enter(r18);
        r13 = r3.openCount;	 Catch:{ all -> 0x004e }
        r0 = r18;
        r14 = r0.maxConnectionCount;	 Catch:{ all -> 0x004e }
        if (r13 < r14) goto L_0x0051;
    L_0x0040:
        r7 = new com.koushikdutta.async.future.SimpleCancellable;	 Catch:{ all -> 0x004e }
        r7.<init>();	 Catch:{ all -> 0x004e }
        r13 = r3.queue;	 Catch:{ all -> 0x004e }
        r0 = r19;
        r13.add(r0);	 Catch:{ all -> 0x004e }
        monitor-exit(r18);	 Catch:{ all -> 0x004e }
        goto L_0x001a;
    L_0x004e:
        r13 = move-exception;
        monitor-exit(r18);	 Catch:{ all -> 0x004e }
        throw r13;
    L_0x0051:
        r13 = r3.openCount;	 Catch:{ all -> 0x004e }
        r13 = r13 + 1;
        r3.openCount = r13;	 Catch:{ all -> 0x004e }
        r0 = r19;
        r13 = r0.state;	 Catch:{ all -> 0x004e }
        r14 = new java.lang.StringBuilder;	 Catch:{ all -> 0x004e }
        r14.<init>();	 Catch:{ all -> 0x004e }
        r15 = r18.getClass();	 Catch:{ all -> 0x004e }
        r15 = r15.getCanonicalName();	 Catch:{ all -> 0x004e }
        r14 = r14.append(r15);	 Catch:{ all -> 0x004e }
        r15 = ".owned";
        r14 = r14.append(r15);	 Catch:{ all -> 0x004e }
        r14 = r14.toString();	 Catch:{ all -> 0x004e }
        r15 = 1;
        r15 = java.lang.Boolean.valueOf(r15);	 Catch:{ all -> 0x004e }
        r13.put(r14, r15);	 Catch:{ all -> 0x004e }
    L_0x007e:
        r13 = r3.sockets;	 Catch:{ all -> 0x004e }
        r13 = r13.isEmpty();	 Catch:{ all -> 0x004e }
        if (r13 != 0) goto L_0x00ca;
    L_0x0086:
        r13 = r3.sockets;	 Catch:{ all -> 0x004e }
        r2 = r13.pop();	 Catch:{ all -> 0x004e }
        r2 = (com.koushikdutta.async.http.AsyncSocketMiddleware.IdleSocketHolder) r2;	 Catch:{ all -> 0x004e }
        r9 = r2.socket;	 Catch:{ all -> 0x004e }
        r14 = r2.idleTime;	 Catch:{ all -> 0x004e }
        r0 = r18;
        r13 = r0.idleTimeoutMs;	 Catch:{ all -> 0x004e }
        r0 = (long) r13;	 Catch:{ all -> 0x004e }
        r16 = r0;
        r14 = r14 + r16;
        r16 = java.lang.System.currentTimeMillis();	 Catch:{ all -> 0x004e }
        r13 = (r14 > r16 ? 1 : (r14 == r16 ? 0 : -1));
        if (r13 >= 0) goto L_0x00a7;
    L_0x00a3:
        r9.close();	 Catch:{ all -> 0x004e }
        goto L_0x007e;
    L_0x00a7:
        r13 = r9.isOpen();	 Catch:{ all -> 0x004e }
        if (r13 == 0) goto L_0x007e;
    L_0x00ad:
        r0 = r19;
        r13 = r0.request;	 Catch:{ all -> 0x004e }
        r14 = "Reusing keep-alive socket";
        r13.logd(r14);	 Catch:{ all -> 0x004e }
        r0 = r19;
        r13 = r0.connectCallback;	 Catch:{ all -> 0x004e }
        r14 = 0;
        r13.onConnectCompleted(r14, r9);	 Catch:{ all -> 0x004e }
        r8 = new com.koushikdutta.async.future.SimpleCancellable;	 Catch:{ all -> 0x004e }
        r8.<init>();	 Catch:{ all -> 0x004e }
        r8.setComplete();	 Catch:{ all -> 0x004e }
        monitor-exit(r18);	 Catch:{ all -> 0x004e }
        r7 = r8;
        goto L_0x001a;
    L_0x00ca:
        monitor-exit(r18);	 Catch:{ all -> 0x004e }
        r0 = r18;
        r13 = r0.connectAllAddresses;
        if (r13 == 0) goto L_0x00e1;
    L_0x00d1:
        r0 = r18;
        r13 = r0.proxyHost;
        if (r13 != 0) goto L_0x00e1;
    L_0x00d7:
        r0 = r19;
        r13 = r0.request;
        r13 = r13.getProxyHost();
        if (r13 == 0) goto L_0x016a;
    L_0x00e1:
        r0 = r19;
        r13 = r0.request;
        r14 = "Connecting socket";
        r13.logd(r14);
        r6 = 0;
        r0 = r19;
        r13 = r0.request;
        r13 = r13.getProxyHost();
        if (r13 == 0) goto L_0x0139;
    L_0x00f5:
        r0 = r19;
        r13 = r0.request;
        r10 = r13.getProxyHost();
        r0 = r19;
        r13 = r0.request;
        r11 = r13.getProxyPort();
        r0 = r19;
        r13 = r0.request;
        r13 = r13.getHeaders();
        r13 = r13.getHeaders();
        r0 = r19;
        r14 = r0.request;
        r14 = r14.getProxyRequestLine();
        r14 = r14.toString();
        r13.setStatusLine(r14);
        r6 = 1;
    L_0x0121:
        r0 = r18;
        r13 = r0.mClient;
        r13 = r13.getServer();
        r0 = r19;
        r14 = r0.connectCallback;
        r0 = r18;
        r14 = r0.wrapCallback(r14, r12, r5, r6);
        r7 = r13.connectSocket(r10, r11, r14);
        goto L_0x001a;
    L_0x0139:
        r0 = r18;
        r13 = r0.proxyHost;
        if (r13 == 0) goto L_0x0164;
    L_0x013f:
        r0 = r18;
        r10 = r0.proxyHost;
        r0 = r18;
        r11 = r0.proxyPort;
        r0 = r19;
        r13 = r0.request;
        r13 = r13.getHeaders();
        r13 = r13.getHeaders();
        r0 = r19;
        r14 = r0.request;
        r14 = r14.getProxyRequestLine();
        r14 = r14.toString();
        r13.setStatusLine(r14);
        r6 = 1;
        goto L_0x0121;
    L_0x0164:
        r10 = r12.getHost();
        r11 = r5;
        goto L_0x0121;
    L_0x016a:
        r0 = r19;
        r13 = r0.request;
        r14 = "Resolving domain and connecting to all available addresses";
        r13.logv(r14);
        r0 = r18;
        r13 = r0.mClient;
        r13 = r13.getServer();
        r14 = r12.getHost();
        r13 = r13.getAllByName(r14);
        r14 = new com.koushikdutta.async.http.AsyncSocketMiddleware$1;
        r0 = r18;
        r1 = r19;
        r14.<init>(r1, r5, r12);
        r13 = r13.then(r14);
        r13 = (com.koushikdutta.async.future.Cancellable) r13;
        r7 = r13;
        goto L_0x001a;
        */
        throw new UnsupportedOperationException("Method not decompiled: com.koushikdutta.async.http.AsyncSocketMiddleware.getSocket(com.koushikdutta.async.http.AsyncHttpClientMiddleware$GetSocketData):com.koushikdutta.async.future.Cancellable");
    }

    private ConnectionInfo getOrCreateConnectionInfo(String lookup) {
        ConnectionInfo info = (ConnectionInfo) this.connectionInfo.get(lookup);
        if (info != null) {
            return info;
        }
        info = new ConnectionInfo();
        this.connectionInfo.put(lookup, info);
        return info;
    }

    private void maybeCleanupConnectionInfo(String lookup) {
        ConnectionInfo info = (ConnectionInfo) this.connectionInfo.get(lookup);
        if (info != null) {
            while (!info.sockets.isEmpty()) {
                IdleSocketHolder idleSocketHolder = (IdleSocketHolder) info.sockets.peekLast();
                AsyncSocket asyncSocket = idleSocketHolder.socket;
                if (idleSocketHolder.idleTime + ((long) this.idleTimeoutMs) > System.currentTimeMillis()) {
                    break;
                }
                info.sockets.pop();
                asyncSocket.close();
            }
            if (info.openCount == 0 && info.queue.isEmpty() && info.sockets.isEmpty()) {
                this.connectionInfo.remove(lookup);
            }
        }
    }

    private void recycleSocket(AsyncSocket socket, AsyncHttpRequest request) {
        if (socket != null) {
            final ArrayDeque<IdleSocketHolder> sockets;
            Uri uri = request.getUri();
            final String lookup = computeLookup(uri, getSchemePort(uri), request.getProxyHost(), request.getProxyPort());
            final IdleSocketHolder idleSocketHolder = new IdleSocketHolder(socket);
            synchronized (this) {
                sockets = getOrCreateConnectionInfo(lookup).sockets;
                sockets.push(idleSocketHolder);
            }
            final AsyncSocket asyncSocket = socket;
            socket.setClosedCallback(new CompletedCallback() {
                public void onCompleted(Exception ex) {
                    synchronized (AsyncSocketMiddleware.this) {
                        sockets.remove(idleSocketHolder);
                        asyncSocket.setClosedCallback(null);
                        AsyncSocketMiddleware.this.maybeCleanupConnectionInfo(lookup);
                    }
                }
            });
        }
    }

    private void idleSocket(final AsyncSocket socket) {
        socket.setEndCallback(new CompletedCallback() {
            public void onCompleted(Exception ex) {
                socket.close();
            }
        });
        socket.setWriteableCallback(null);
        socket.setDataCallback(new NullDataCallback() {
            public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
                super.onDataAvailable(emitter, bb);
                bb.recycle();
                socket.close();
            }
        });
    }

    private void nextConnection(AsyncHttpRequest request) {
        Uri uri = request.getUri();
        String key = computeLookup(uri, getSchemePort(uri), request.getProxyHost(), request.getProxyPort());
        synchronized (this) {
            ConnectionInfo info = (ConnectionInfo) this.connectionInfo.get(key);
            if (info == null) {
                return;
            }
            info.openCount--;
            while (info.openCount < this.maxConnectionCount && info.queue.size() > 0) {
                GetSocketData gsd = (GetSocketData) info.queue.remove();
                SimpleCancellable socketCancellable = gsd.socketCancellable;
                if (!socketCancellable.isCancelled()) {
                    socketCancellable.setParent(getSocket(gsd));
                }
            }
            maybeCleanupConnectionInfo(key);
        }
    }

    public void onRequestComplete(OnRequestCompleteData data) {
        if (((Boolean) data.state.get(getClass().getCanonicalName() + ".owned", Boolean.valueOf(false))).booleanValue()) {
            try {
                idleSocket(data.socket);
                if (data.exception != null || !data.socket.isOpen()) {
                    data.request.logv("closing out socket (exception)");
                    data.socket.close();
                } else if (HttpUtil.isKeepAlive(data.headers.getHeaders()) && HttpUtil.isKeepAlive(data.request.getHeaders().getHeaders())) {
                    data.request.logd("Recycling keep-alive socket");
                    recycleSocket(data.socket, data.request);
                    nextConnection(data.request);
                } else {
                    data.request.logv("closing out socket (not keep alive)");
                    data.socket.close();
                    nextConnection(data.request);
                }
            } finally {
                nextConnection(data.request);
            }
        }
    }
}
